package com.collegeproject.weatherapp.fragments;

import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.collegeproject.weatherapp.R;
import com.collegeproject.weatherapp.StartActivity.FragmentListener;
import com.collegeproject.weatherapp.library.AsyncResponse;
import com.collegeproject.weatherapp.library.ConnectionDetector;
import com.collegeproject.weatherapp.library.HTTPfunctions;

public class PassRecoveryFragment extends Fragment implements AsyncResponse {

	Button btnRecover, btnBack;
	EditText inputUserName, inputEmail;
	TextView passRecoveryError;

	static FragmentListener _listener;
	ConnectionDetector cd;

	private String mUserName, mEmail;

	private static final String TAG = "PassRecoveryFragment";
	private static final String POSTAUTH = "POSTAUTH";
	// private static String localPassRecURL = "http://10.0.2.2:8080/WeatherAppService.svc/rest/passrecovery";
	private static String passRecURL = "http://x00068868.cloudapp.net/WeatherAppService/rest/passrecovery";

	public static PassRecoveryFragment newInstance(FragmentListener listener) {
		PassRecoveryFragment f = new PassRecoveryFragment();
		_listener = listener;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.pass_recovery, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initialiseViews();
		cd = new ConnectionDetector(getActivity());
	}

	@Override
	public void onStart() {
		
		inputEmail.setOnEditorActionListener(new OnEditorActionListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				
				if (actionId == EditorInfo.IME_ACTION_SEND) {

					mUserName = inputUserName.getText().toString().trim();
					mEmail = inputEmail.getText().toString().trim();

					// try to recover
					attemptRecovery(mUserName, mEmail);

					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);					
					
					return true;
				}
				return false;
			}
		});
		
		inputUserName.setOnEditorActionListener(new OnEditorActionListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				
				if (actionId == EditorInfo.IME_ACTION_SEND) {

					mUserName = inputUserName.getText().toString().trim();
					mEmail = inputEmail.getText().toString().trim();

					// recover
					attemptRecovery(mUserName, mEmail);

					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);					
					
					return true;
				}
				return false;
			}
		});

		// back to login fragment
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// back to login fragment
				_listener.onSwitchToNextFragment();

			}
		});

		// try to register
		btnRecover.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUserName = inputUserName.getText().toString().trim();
				mEmail = inputEmail.getText().toString().trim();

				// try to recover
				attemptRecovery(mUserName, mEmail);
			}
		});
		super.onStart();
	}

	private void attemptRecovery(String mUserName, String mEmail) {

		inputUserName.setError(null);
		inputEmail.setError(null);

		boolean cancel = false;
		View focusView = null;

		// Check for a valid user name.
		if (TextUtils.isEmpty(mUserName)) {

			// check for valid email address
			if (!mEmail.contains("@")) {
				inputEmail.setError(getString(R.string.error_invalid_email));
				focusView = inputEmail;
				cancel = true;
			}
		}

		if (cancel) {
			focusView.requestFocus();
		} else {

			try {
				Boolean connected = cd.isConnectingToInternet();
				if (connected){

					String source = mUserName + ":" + mEmail;
					String base64 = Base64.encodeToString(
							source.getBytes("UTF-8"), Base64.URL_SAFE
									| Base64.NO_WRAP);

					// call the register web service
					HTTPfunctions task = new HTTPfunctions(getActivity(),
							POSTAUTH, base64);
					task.listener = this;
					task.execute(new String[] { passRecURL });
				} else {
					passRecoveryError
							.setText("No internet connection available");
					passRecoveryError.setVisibility(View.VISIBLE);
				}
			} catch (Exception ex) {
				Log.e(TAG, "Attempt pass recovery " + ex.getMessage());
			}
		}
	}

	private void initialiseViews() {
		btnBack = (Button) getView().findViewById(R.id.button_passRec_back);
		btnRecover = (Button) getView().findViewById(
				R.id.button_passRec_recover);

		inputUserName = (EditText) getView().findViewById(
				R.id.editTextPassRecUsername);

		inputEmail = (EditText) getView().findViewById(
				R.id.editTextPassRecEmail);

		passRecoveryError = (TextView) getView().findViewById(
				R.id.passRec_error);
	}

	@Override
	public void processFinish(String result) {
		try {
			JSONObject jsonObject = new JSONObject(result);
			int success = Integer.parseInt(jsonObject.getString("Success"));
			if (success == 0) {
				// toast to user of confirmation of registration
				Toast.makeText(getActivity(),
						jsonObject.getString("ErrorMessage"), Toast.LENGTH_LONG)
						.show();

				// switch to login fragment
				_listener.onSwitchToNextFragment();

			} else {
				// display error from result
				passRecoveryError.setText(jsonObject.getString("ErrorMessage"));
				passRecoveryError.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			Log.e(TAG, "Pass recovery processs result " + e.getMessage());
		}
	}
}
